package com.weavernorth.util;

import weaver.general.BaseBean;
import weaver.general.Util;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.util
 * @date: 2020/7/29 10:06
 * @description:
 */
public class dateUtils {
    /***
     * 判断日期是否在某个范围内
     * @param nowDate
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public static boolean dateBetween(String nowDate, String startDate, String endDate) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date now = format.parse(nowDate);
        Date start = format.parse(startDate);
        Date end = format.parse(endDate);

        long nowTime = now.getTime();
        long startTime = start.getTime();
        long endTime = end.getTime();

        return nowTime >= startTime && nowTime <= endTime;
    }

    /***
     * 判断日期 时间是否在某个范围内
     * @param nowDate
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public static boolean dateTimeBetween(String nowDate, String startDate, String endDate) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date now = format.parse(nowDate);
        Date start = format.parse(startDate);
        Date end = format.parse(endDate);
        long nowTime = now.getTime();
        long startTime = start.getTime();
        long endTime = end.getTime();
        return nowTime >= startTime && nowTime <= endTime;
    }
    /***
     * 比较两个日期大小
     * @param date1
     * @param date2
     * @return
     * @throws Exception
     */
    public static boolean dateCompare(String date1, String date2) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date v1 = format.parse(date1);
        Date v2 = format.parse(date2);
        long datetime1 = v1.getTime();
        long datetime2 = v2.getTime();
        return datetime1 < datetime2;
    }
    /***
     * 获取当前日期 时间（格式："yyyy-MM-dd HH:mm:ss"）
     * @return
     */
    public static String getNowDateTime()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());//设置当前日期
        //格式化日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime  = sdf.format(calendar.getTime());
        return dateTime;
    }
    /***
     * 获取当前日期（格式："yyyy-MM-dd"）
     * @return
     */
    public static String getYearMonthDay()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());//设置当前日期
        //格式化日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String yearMonthDay  = sdf.format(calendar.getTime());
        return yearMonthDay;
    }

    /***
     * 获取当前时间
     * @return
     */
    public static String getHourMs()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());//设置当前日期
        //格式化日期
        SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
        String HourMs  = sdf.format(calendar.getTime());
        return HourMs;
    }
    /***
     * 获取上个月日期（格式："yyyy-MM-dd"）
     * @return
     */
    public static String getPreviousMonthDate(){
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(new Date());//设置当前日期
        calendar.add(Calendar.MONTH, -1);
        //格式化日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String result  =sdf.format(calendar.getTime());
        return result;
    }
    /***
     * 获取当前日期上个月的年,月
     * @return
     */
    public static String previousMonth(){
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(new Date());//设置当前日期
        calendar.add(Calendar.MONTH, -1);
        String[] strNow = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()).toString().split("-");
        Integer year = Integer.parseInt(strNow[0]);
        Integer monthInt = Integer.parseInt(strNow[1]);
        String month="0";
        if (monthInt<10){
            month="0"+ Util.null2String(monthInt);
        }else{
            month=Util.null2String(monthInt);
        }
        return year+month;
    }
    /***
     * 获取当前日期前N个月的年,月
     * @return
     */
    public static String previousMonth(Integer n){
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(new Date());//设置当前日期
        calendar.add(Calendar.MONTH, n);
        String[] strNow = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()).toString().split("-");
        Integer year = Integer.parseInt(strNow[0]);
        Integer monthInt = Integer.parseInt(strNow[1]);
        String month="0";
        if (monthInt<10){
            month="0"+Util.null2String(monthInt);
        }else{
            month=Util.null2String(monthInt);
        }
        return year+month;
    }
    /***
     * 获取当前考核周期的上个周期
     * @return
     */
    public static String previousMonth(String khzq){
        String year="";
        String month="";
        try{
            if (khzq.length()>0){
                year=khzq.substring(0,4);
                Integer monthInt = Integer.parseInt(khzq.substring(4,6));
                if (monthInt>1&&monthInt<=10){
                    month="0"+Util.null2String(monthInt-1);
                }else if(monthInt>10){
                    month=Util.null2String(monthInt-1);
                }else{
                    year=Util.null2String(Integer.parseInt(year)-1);
                    month="12";
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return year+month;
    }

    /***
     * 取某年某月最后一天的日期
     * @param year
     * @param month
     * @return
     */
    public static String LastDayOfMonth(int year,int month)
    {
        Calendar calendar = Calendar.getInstance();
        //设置年
        calendar.set(Calendar.YEAR,year);
        //设置月
        calendar.set(Calendar.MONTH,month-1);
        //获取某月最大天数
        BaseBean bb=new BaseBean();
        bb.writeLog("获取某月最大天数");
        int lastDay=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        bb.writeLog("某月最大天数为。。"+lastDay);
        //设置日历中月份的最大天数
        bb.writeLog("设置日历中月份的最大天数。。");
        calendar.set(Calendar.DAY_OF_MONTH,lastDay);
        //格式化日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth  = sdf.format(calendar.getTime());
        bb.writeLog("格式化日期。。"+lastDayOfMonth+"");
        return lastDayOfMonth;
    }

    public static int getMonthByjd(int jd){
        int result=0;
        switch (jd){
            case 1:
                result=3;
                break;
            case 2:
                result=6;
                break;
            case 3:
                result=9;
                break;
            case 4:
                result=12;
                break;
        }
        return result;
    }

    /***
     * 获取某年某月最后一天
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    /***
     * 获取当前日期上个月的最后一天
     * @param strDate:yyyy-MM-dd
     * @return
     */
    public static String getLastDate(String strDate){
        int year= Integer.parseInt(strDate.substring(0,4));
        int month= Integer.parseInt(strDate.substring(5,7));
        if (month<2){
            year=year-1;
            month=12;
        }else{
            month=month-1;
        }
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    /**
     * 获取上一个月的第一天日期
     *
     * @return
     */
    public static String getPreMonthFirstDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return format.format(calendar.getTime());
    }

    /**
     * 获取上一个月的最后一天日期
     *
     * @return
     */
    public static String getPreMonthLastDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return format.format(calendar.getTime());
    }


    /**
    /***
     * 验证日期是否合法，日期格式传入yyyy-MM-dd，如2018-1-1或者2018-01-01格式
     * @param strDate
     * @return
     */
    public static boolean isValidDate(String strDate,String pattern) {
        String strPattern="yyyy-MM-dd HH:mm:ss";
        if(!"".equals(pattern)){
            strPattern=pattern;
        }
        SimpleDateFormat format = new SimpleDateFormat(strPattern);
        try {
            format.setLenient(false);
            format.parse(strDate);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /***
     * 获取两个时间差：相差秒数
     * @param end 结束时间
     * @param start 开始时间
     * @return 时间差(秒数)
     * @throws ParseException
     */
    private static long getTimeDiffer(String end, String start) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        long NTime = 0;
        long OTime = 0;
        long diff= 0;
            NTime = df.parse(end).getTime();
            OTime = df.parse(start).getTime();
            diff=(NTime-OTime)/1000;
        return diff;
    }

    private static transient int gregorianCutoverYear = 1582;

    /** 闰年中每月天数 */
    private static final int[] DAYS_P_MONTH_LY= {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /** 非闰年中每月天数 */
    private static final int[] DAYS_P_MONTH_CY= {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /** 代表数组里的年、月、日 */
    private static final int Y = 0, M = 1, D = 2;

    /**
     * 将代表日期的字符串分割为代表年月日的整形数组
     * @param date
     * @return
     */
    public static int[] splitYMD(String date){
        date = date.replace("-", "");
        int[] ymd = {0, 0, 0};
        ymd[Y] = Integer.parseInt(date.substring(0, 4));
        ymd[M] = Integer.parseInt(date.substring(4, 6));
        ymd[D] = Integer.parseInt(date.substring(6, 8));
        return ymd;
    }

    /**
     * 检查传入的参数代表的年份是否为闰年
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {
        return year >= gregorianCutoverYear ?
                ((year%4 == 0) && ((year%100 != 0) || (year%400 == 0))) : (year%4 == 0);
    }

    /**
     * 日期加1天
     * @param year
     * @param month
     * @param day
     * @return
     */
    private static int[] addOneDay(int year, int month, int day){
        if(isLeapYear( year )){
            day++;
            if( day > DAYS_P_MONTH_LY[month -1 ] ){
                month++;
                if(month > 12){
                    year++;
                    month = 1;
                }
                day = 1;
            }
        }else{
            day++;
            if( day > DAYS_P_MONTH_CY[month -1 ] ){
                month++;
                if(month > 12){
                    year++;
                    month = 1;
                }
                day = 1;
            }
        }
        int[] ymd = {year, month, day};
        return ymd;
    }

    /**
     * 将不足两位的月份或日期补足为两位
     * @param decimal
     * @return
     */
    public static String formatMonthDay(int decimal){
        DecimalFormat df = new DecimalFormat("00");
        return df.format( decimal );
    }

    /**
     * 将不足四位的年份补足为四位
     * @param decimal
     * @return
     */
    public static String formatYear(int decimal){
        DecimalFormat df = new DecimalFormat("0000");
        return df.format( decimal );
    }

    /**
     * 计算两个日期之间相隔的天数
     * @param begin
     * @param end
     * @return
     * @throws ParseException
     */
    public static long countDay(String begin,String end){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate , endDate;
        long day = 0;
        try {
            beginDate= format.parse(begin);
            endDate= format.parse(end);
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }

    /**
     * 获取日期段内每一天的日期
     * @param beginDate endDate
     * @param endDate
     * @return
     */
    public static List<String> getEveryday(String beginDate , String endDate){
        long days = countDay(beginDate, endDate);
        int[] ymd = splitYMD( beginDate );
        List<String> everyDays = new ArrayList<String>();
        everyDays.add(beginDate);
        for(int i = 0; i < days; i++){
            ymd = addOneDay(ymd[Y], ymd[M], ymd[D]);
            everyDays.add(formatYear(ymd[Y])+"-"+formatMonthDay(ymd[M])+"-"+formatMonthDay(ymd[D]));
        }
        return everyDays;
    }

    /***
     * 获取日期为周几
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static String getWeekDays(String strDate) throws ParseException {
        SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd");
        Date newDate = dateFm.parse(strDate);
        SimpleDateFormat newDateFm = new SimpleDateFormat("EEEE");
        String weekDays = newDateFm.format(newDate.getTime());
        Map<String,String> mp=new HashMap<>();
        mp.put("星期一","0");
        mp.put("星期二","1");
        mp.put("星期三","2");
        mp.put("星期四","3");
        mp.put("星期五","4");
        mp.put("星期六","5");
        mp.put("星期日","6");
        return mp.get(weekDays);
    }
}
